package cn.audit.controller.zqmk;

import cn.audit.bean.pojo.KnowledgeBase;
import cn.audit.repository.zqmk.KnowledgeBaseRepository;
import org.apache.commons.io.FileUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.UUID;

/**
 * @Author: 钟琪
 * @Date: 2019/5/25 11:06
 */
@Controller
public class RepositoryController {
    @Resource
    private KnowledgeBaseRepository knowledgeBaseRepository;

    @RequestMapping("/repository")
    public String repository(@RequestParam(value = "page",defaultValue = "0") Integer page,Model model) {

        Pageable pageable=PageRequest.of(page,10);//pageRequest借口实现类
        Page<KnowledgeBase> list=knowledgeBaseRepository.findAll(pageable);
        System.out.println(list.getContent());//得到数据列表
        System.out.println(list.getTotalElements());//得到总条数
        System.out.println(list.getTotalPages());//得到总页数
        model.addAttribute("list",list.getContent());
        model.addAttribute("page",page);
        model.addAttribute("total",list.getTotalElements());//总条数
        model.addAttribute("pages",list.getTotalPages()-1);
        return "/repository";
    }


    @RequestMapping("/del")
    public String del(Long id){
        knowledgeBaseRepository.deleteById(id);
        return "redirect:/repository";
    }



    @RequestMapping("/upload")
    public String upload(MultipartFile file, @RequestParam(value = "g") String [] g) throws IOException, ParseException {

        String d="";
        for(int i=0;i<g.length;i++){
                d=d+g[i];
            if(!(i==g.length-1)){
                d=d+",";
            }
        }
        System.out.println(d);
        String uuid=UUID.randomUUID().toString();
      String fileName = file.getOriginalFilename();
        KnowledgeBase k=new KnowledgeBase();
        k.setName(fileName);
        Date date=new Date();

        String path="D:/hhh/SecuritiesAudit/SecuritiesAudit/src/main/resources/static/wenjian/";
        path=path+fileName;
        k.setPath(path);
        k.setCreationDate(date);
        k.setPoint(d);
        k.setStatus(1);
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path));
            knowledgeBaseRepository.save(k);



            return "redirect:/repository";
        } catch (IOException e) {
            return "redirect:/repository";
        }

    }


}
